#!/bin/bash

# 设置颜色变量
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m'

# 检查是否为root用户
if [ "$(id -u)" != "0" ]; then
    echo -e "${RED}错误：请使用 root 用户运行此脚本${NC}"
    exit 1
fi

# 安装必要的系统工具
echo -e "${CYAN}安装必要的系统工具...${NC}"
apt-get update
apt-get install -y \
    apt-transport-https \
    ca-certificates \
    curl \
    gnupg \
    lsb-release \
    software-properties-common \
    net-tools \
    wget \
    git

# 检查是否已安装Docker
if command -v docker &> /dev/null; then
    echo -e "${YELLOW}检测到Docker已安装，正在卸载旧版本...${NC}"
    apt-get remove -y docker docker-engine docker.io containerd runc
fi

# 添加Docker官方GPG密钥
echo -e "${CYAN}添加Docker官方GPG密钥...${NC}"
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg

# 设置Docker稳定版仓库
echo -e "${CYAN}设置Docker仓库...${NC}"
echo \
  "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu \
  $(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null

# 更新apt包索引
echo -e "${CYAN}更新包索引...${NC}"
apt-get update

# 安装Docker Engine和Docker Compose
echo -e "${CYAN}安装Docker Engine和必要组件...${NC}"
apt-get install -y docker-ce docker-ce-cli containerd.io

# 安装Docker Compose V2
echo -e "${CYAN}安装Docker Compose...${NC}"
mkdir -p /usr/local/lib/docker/cli-plugins/
curl -SL "https://github.com/docker/compose/releases/download/v2.20.3/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/lib/docker/cli-plugins/docker-compose
chmod +x /usr/local/lib/docker/cli-plugins/docker-compose

# 启动Docker服务
echo -e "${CYAN}启动Docker服务...${NC}"
systemctl start docker
systemctl enable docker

# 配置Docker镜像加速
echo -e "${CYAN}配置Docker镜像加速...${NC}"
mkdir -p /etc/docker
cat > /etc/docker/daemon.json <<EOF
{
  "registry-mirrors": [
    "https://mirror.ccs.tencentyun.com",
    "https://hub-mirror.c.163.com",
    "https://mirror.baidubce.com"
  ]
}
EOF

# 重启Docker服务以应用镜像加速
echo -e "${CYAN}重启Docker服务...${NC}"
systemctl daemon-reload
systemctl restart docker

# 验证安装
echo -e "${CYAN}验证Docker安装...${NC}"
if docker --version && docker compose version; then
    echo -e "${GREEN}Docker 安装成功！${NC}"
    echo -e "${GREEN}Docker Compose 安装成功！${NC}"
    
    # 显示Docker版本信息
    echo -e "\n${YELLOW}Docker 版本信息：${NC}"
    docker --version
    echo -e "\n${YELLOW}Docker Compose 版本信息：${NC}"
    docker compose version
    
    # 显示Docker服务状态
    echo -e "\n${YELLOW}Docker 服务状态：${NC}"
    systemctl status docker --no-pager
else
    echo -e "${RED}Docker 安装失败，请检查错误信息${NC}"
    exit 1
fi

# 安装完成
echo -e "\n${GREEN}Docker环境配置完成！${NC}"
echo -e "${BLUE}系统将在5秒后继续...${NC}"
sleep 5

exit 0 